$(function () {
    var courseId = $("#courseId").val();
    //初始化课程目录
    initCourseCatalog();
    $("body").on('ifClicked','[name="studyLimit"]',function (evnt) {// 学习限制
        var studyLimit = $(this).val();
        if(studyLimit==3){
            $(".score-percent-box").removeClass("hide");
        }else{
            $(".score-percent-box").addClass("hide");
            updateCourseStudyLimit(courseId,studyLimit,0.0);
        }
    }).on('focus',"input[name='scorePercent']",function () {
        var _score = $(this).val();
        if(_score=='0.0'){
            $(this).val('');
        }
    }).on('blur',"input[name='scorePercent']",function () {// 得分率输入监听
        var val = $(this).val();
        if(!/^[0-9]+(.[0-9]{1,2})*$/.test(val)){
            $(this).val('0.0');
        }
        updateCourseStudyLimit(courseId,3,$(this).val())
    }).on('click','#appendCatalog',function () {//新建章节
        initUpdateAdd(courseId,0,0);
    }).on('click','#saveCancel',function () {//确定并返回
        var courseTypeKey = $("#courseTypeKey").val();
        if(courseTypeKey=="LIVE"){
            window.location.href= baseloaction +'/admin/course/live/liveList';
        }else if(courseTypeKey=="COLUMNS" || courseTypeKey=="VIDEO"){
            window.location.href= baseloaction +'/admin/course/cou/courseList';
        }else if(courseTypeKey=="SMALL"){
            window.location.href=baseloaction+'/admin/course/small/smallCourseList'
        }
    }).on('click','#selectMould',function () {//选择模块
        var subjectIds = $("#subjectIds").val();
        selectMould('checkbox',subjectIds,courseId,1);
    }).on('keyup','#search',function () {//高亮搜索
        var keyword = $(this).val();
        var treeObj = $.fn.zTree.getZTreeObj("ztree");
        var list = treeObj.getNodesByFilter(function (node) {
            return true;
        });

        if(!$.isEmptyObject(list) && list.length>0){
            $.each(list,function (index,node){
                node.highlight  = false;
                treeObj.updateNode(node);
            });
        }
        var nodes = treeObj.getNodesByFilter(function (node) {
            if(!$.isEmptyObject(keyword) && $.trim(keyword)!='' && node.catalogName.indexOf(keyword)!=-1){
                return true;
            }else{
                return false;
            }
        });
        if(!$.isEmptyObject(nodes) && nodes.length>0){
            $.each(nodes,function (index,node) {
                node.highlight=true;
                treeObj.updateNode(node);
                treeObj.expandNode(node,true,true,true);
                var parentNode = node.getParentNode();
                if(parentNode!=null){
                    treeObj.expandNode(parentNode,true,true,true);
                }
            });
        }
    });

    /**
     * 更新课程的学习顺序
     * @param courseId 课程ID
     * @param studyLimit 学员顺序
     * @param scorePercent 得分率
     */
    function updateCourseStudyLimit(courseId,studyLimit,scorePercent) {
        if(scorePercent==0.0&&studyLimit==3){
            icModale(0,"随堂练习模式，得分率必须大于0");
            return;
        }
        $.ajax({
            url:baseloaction + '/admin/course/cou/updateCourseStudyLimit',
            type:'post',
            dataType:'json',
            data:{
                'courseId':courseId,
                'studyLimit':studyLimit,
                'scorePercent':scorePercent
            }
        });
    }

    /**
     * 初始化课程目录
     */
    function initCourseCatalog() {
        var settings = {
            async: {
                dataType: 'json',
                dataFilter: function (treeId, treeNode, response) {
                    if (response.success) {
                        var list = response.entity;
                        if(list!=null && list.length>0){
                            $.each(list,function (index,em) {
                                var videoDuration = em.videoDuration;

                                if(em.materialId==0&&em.nodeType==2){
                                    em.catalogName = em.catalogName+'(没有学习资源)';
                                }else if(em.materialTypeKey=="LIVE"&&em.nodeType==2){
                                    var strTime = longTimeToStr(videoDuration);
                                    em.catalogName = "[直播-"+strTime+"]"+em.catalogName+' ['+em.lessonStartTime.replace(/-/g,"/")+' - '+em.lessonEndTime.replace(/-/g,"/")+']';
                                }else if(em.nodeType==2){
                                    var strTime = longTimeToStr(videoDuration);

                                    var type ="";
                                    switch ( em.materialTypeKey) {
                                        case "VIDEO":
                                            type="视频";
                                            break;
                                        case "AUDIO":
                                            type="音频";
                                            break;
                                        case "ARTICLE":
                                            type="文章";
                                            break;

                                    }
                                    em.catalogName = "["+type+"-"+strTime+"] "+em.catalogName;
                                    if (em.questionIds!=null&&em.questionIds!=""){
                                        em.catalogName ="[随堂练习] "+em.catalogName;
                                    }
                                }
                            });
                        }
                        return response.entity;
                    } else {
                        icModale(0, response.message);
                    }
                },
                enable: true,
                type: 'post',
                url: baseloaction + "/admin/course/catalog/findCourseCatalog?courseId=" + $('#courseId').val()
            },
            check: {
                enable: false
            },
            data: {
                key: {
                    name: 'catalogName',
                    title: 'catalogName',
                    mId: 'mouldId'
                },
                simpleData: {
                    enable: true,
                    idKey: 'id',
                    pIdKey: 'parentId',
                    rootPId: null
                }
            },
            edit: {
                drag: {
                    isMove: true
                },
                enable: true,
                removeTitle: function (treeId, treeNode) {
                    if (treeNode.isParent) {
                        return "删除：" + treeNode.catalogName + '及其子节点';
                    } else {
                        return "删除：" + treeNode.catalogName;
                    }
                },
                renameTitle: function (treeId, treeNode) {
                    return "修改：" + treeNode.catalogName;
                },
                showRemoveBtn: true,
                showRenameBtn: true
            },
            view: {
                addHoverDom: function (treeId, treeNode) {
                    var rObj = $("#" + treeNode.tId + "_remove");
                    //-------------自定义排序按钮
                    //获取前一个节点
                    var preNode = treeNode.getPreNode();
                    if(preNode !=null && $("#upBtn_"+treeNode.tId).length <= 0) {//前一个节点存在
                        var upStr = "<span class='button up' id='upBtn_" + treeNode.tId + "' title='向上' onfocus='this.blur();'></span>";
                        rObj.after(upStr);
                        var upBtn = $("#upBtn_" + treeNode.tId);
                        if(upBtn){
                            upBtn.bind("click",function () {
                                var preSort = preNode.sort;
                                var currentSort = treeNode.sort;
                                updateNodeSort(treeNode.id,preSort,preNode.id,currentSort,1);
                            });
                        }
                    }
                    //获取下一下节点
                    var nextNode = treeNode.getNextNode();
                    if(nextNode !=null && $("#downBtn_"+treeNode.tId).length <= 0 ) {//下一下节点存在
                        var downStr = "<span class='button down' id='downBtn_" + treeNode.tId + "' title='向下' onfocus='this.blur();'></span>";
                        rObj.after(downStr);
                        var downBtn = $("#downBtn_" + treeNode.tId);
                        if(downBtn){
                            downBtn.bind("click",function () {
                                var downSort = nextNode.sort;
                                var currentSort = treeNode.sort;
                                updateNodeSort(treeNode.id,downSort,nextNode.id,currentSort,2);
                            });
                        }
                    }
                    if (treeNode.questionIds!=null&&$("#practice_" + treeNode.tId).length<=0){
                    var addStrTo = "<span class='button list' id='practice_" + treeNode.tId + "' title='查看随堂练习' onfocus='this.blur();'></span>";
                     rObj.after(addStrTo);
                    var btn = $("#practice_" + treeNode.tId);
                        if (btn) btn.bind("click", function () {
                            lookPractice(courseId);
                        });
                    }
                    var sObj = $("#" + treeNode.tId + "_span");
                    //====================================================
                    if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0 || treeNode.level > 0 || treeNode.nodeType==2) return;
                    var addStr = "<span class='button add' id='addBtn_" + treeNode.tId + "' title='添加章节' onfocus='this.blur();'></span>";
                    sObj.after(addStr);
                    var btn = $("#addBtn_" + treeNode.tId);
                    if (btn) btn.bind("click", function () {
                        initUpdateAdd(treeNode['courseId'],0,treeNode.id);
                        return false;
                    });
                },
                removeHoverDom: function (treeId, treeNode) {//鼠标离开删除自定义按钮
                    $("#addBtn_" + treeNode.tId).unbind().remove();
                    $("#upBtn_" + treeNode.tId).unbind().remove();
                    $("#downBtn_" + treeNode.tId).unbind().remove();
                    $("#practice_" + treeNode.tId).unbind().remove();

                },
                fontCss: function (treeId, treeNode) {
                    if (typeof treeNode.highlight == 'undefined' || treeNode.highlight == false) {
                        if(treeNode.materialId==0&&treeNode.nodeType==2){
                            return {color:"#dda525", "font-weight":"normal"};
                        }else{
                            return {color:"#333", "font-weight":"normal"};
                        }
                    } else {
                        return {color: "#A60000", "font-weight": "bold"};
                    }
                },
                showLine: true,
                selectedMulti: false
            },
            callback: {
                // moveType 'inner' 'prev' 'next'
                beforeDrop: function (treeId, treeNode, targetNode, moveType, isCopy) {//初始拖动
                    var node = treeNode[0];
                    var reallyLevel = true;
                    if((node.children!=null && node.children.length>0) || (targetNode.getParentNode()!=null) ){
                        reallyLevel = false;
                    }
                    if(reallyLevel==false) {
                        icModale(0, '章节最多支持二级节点');
                        return false;
                    }
                    if ('inner' != moveType && targetNode != null) {
                        targetNode = targetNode.getParentNode();
                    }
                    $.ajax({
                        url: baseloaction + '/admin/course/catalog/updateCatalogParent',
                        data: {
                            'id': treeNode[0].id,
                            'parentId': targetNode.id
                        },
                        dataType: 'json',
                        success: function (response) {
                            icModale(0, response.message);
                            if (response.success) {
                                $.fn.zTree.getZTreeObj('ztree').moveNode(targetNode, treeNode[0], moveType, false);
                            }
                        },
                        error: function () {
                            icModale(0, '系统错误，移动章节节点失败');
                        }
                    });
                    return false;
                },
                beforeEditName: function (treeId, treeNode) {//初始化修改
                    initUpdateAdd(treeNode['courseId'],treeNode.id,0);
                    return false;
                },
                beforeRemove: function (treeId, treeNode) {//删除
                    var msg ="确认要删除该章节吗?";
                    if($("#status").val()=="1"){
                        msg="课程以上架，确认要删除该章节吗可能会影响前台用户数据!!!"
                    }
                    icModale(2, msg,3,function () {
                       $.ajax({
                           url:baseloaction +'/admin/course/catalog/deleteCatalog',
                           type:'post',
                           dataType:'json',
                           data:{'ids':treeNode.id},
                           success:function (result) {
                               if(result.success==true){
                                   var treeObj = $.fn.zTree.getZTreeObj(treeId);
                                   treeObj.removeNode(treeNode);
                                   showHide(treeObj);
                                       getTeacherName();
                                      sumDuration();
                               }
                           },
                           error:function (error) {
                               icModale(0, "系统错误，章节删除失败");
                           }
                       });
                    });
                    return false;
                },
                onAsyncError: function (event, treeId, treeNode, request, status) {//异步加载数据失败
                    icModale(0, "系统错误，章节获取失败");
                },
                onAsyncSuccess: function (event, treeId, treeNode, msg) {//异步加载数据成功
                    var treeObj = $.fn.zTree.getZTreeObj(treeId);
                    showHide(treeObj);
                    getTeacherName();
                    sumDuration();
                }
            }
        };
        //初始化权限树
        $.fn.zTree.init($('#ztree'), settings);
    }

    /**
     * 初始化修改/添加目录功能
     * @param courseId 课程ID
     * @param id 目录ID（用于修改，添加传0）
     * @param parentId 父级ID（用于添加，修改传0）
     */
    function initUpdateAdd(courseId,id,parentId) {
        var url = '';
        var title = '';
        if(id>0){//修改
            title = '修改章节';
            url = baseloaction +'/admin/course/catalog/initUpdate?courseId='+courseId+'&id='+id;
        }else{//添加
            title = '创建章节';
            url = baseloaction +'/admin/course/catalog/initAdd?courseId='+courseId+'&parentId='+parentId;
        }
        parent.layer.open({
            type: 2,
            area: winArea,
            btn: ['确定','取消'],
            content:url,
            maxmin: true,
            skin: 'layui-layer-demo',
            title: '<strong>'+title+'</strong>',
            yes: function (index, layero) {
                var frame = parent.layer.getChildFrame('body', index);
                var params = frame.find('#catalogForm').serializeJSON();
                params.lorePointIds = frame.find('#table-loreset-point tr[data-ids]').map(function() {
                    return ',' + this.dataset['ids'] + ',';
                }).get().join('#');
                var questions = frame.find('#course-catalog-question tr[data-question]');
                var practice = 0;
                if (questions.length > 0) {
                    params.questionIds = frame.find('#course-catalog-question tr[data-question]').map(function() {
                        practice += parseInt(this.dataset['score']);
                        return this.dataset['question'];
                    }).get().join(',');
                    params.questionIds = ',' + params.questionIds + ',';
                } else {
                    params.questionIds = '';
                }
                params.practice = practice;
                var replay = params.replay;
                if(typeof  replay =='undefined'){
                    params.replay = 0;
                }
                //获取排序号
                setSortNum(params,id,parentId);
                params = JSON.stringify(params);
                $.ajax({
                    url:baseloaction +'/admin/course/catalog/saveCatalog',
                    type:'post',
                    dataType:'json',
                    data:params,
                    contentType:'application/json;charset=utf-8',
                    success:function (result) {
                        if(result.success==false){
                            icModale(0, result.message);
                        }else{
                            var obj = result.entity;
                            var treeObj = $.fn.zTree.getZTreeObj("ztree");
                            var _id = frame.find('input[name="id"]').val();
                            var videoDuation = obj.videoDuration;
                            if(obj.materialId==0&&obj.nodeType==2){
                                obj.catalogName = obj.catalogName+'(没有学习资源)';
                            }else if(obj.materialTypeKey=="LIVE"&&obj.nodeType==2){
                                var strTime = longTimeToStr(videoDuation);

                                obj.catalogName = "[直播-"+strTime+"] "+obj.catalogName+' ['+obj.lessonStartTime.replace(/-/g,"/")+' - '+obj.lessonEndTime.replace(/-/g,"/")+']';
                            }else if(obj.nodeType==2){
                                var strTime = longTimeToStr(videoDuation);
                                var type ="";
                                switch ( obj.materialTypeKey) {
                                    case "VIDEO":
                                        type="视频";
                                        break;
                                    case "AUDIO":
                                        type="音频";
                                        break;
                                    case "ARTICLE":
                                        type="文章";
                                        break;

                                }
                                obj.catalogName = "["+type+"-"+strTime+"] "+obj.catalogName;
                                if (obj.questionIds!=null&&obj.questionIds!=""){
                                    obj.catalogName ="[随堂练习] "+obj.catalogName;
                                }
                            }
                            if(_id ==null || _id =='' || _id==0){//添加
                                var nodeList = treeObj.getNodesByParam("id",obj.parentId,null);
                                var parentNode = null;
                                if(nodeList!=null && nodeList.length > 0){
                                    parentNode = nodeList[0];
                                }
                                var nodes = new Array();
                                nodes.push(obj);
                                treeObj.addNodes(parentNode,nodes);
                            }else{//修改
                                var node = treeObj.getNodeByParam("id", obj.id, null);
                                node.catalogName = obj.catalogName;
                                treeObj.updateNode(node);
                            }
                            showTree();
                            if(id>=0){//修改
                                sumDuration();
                            }
                            getTeacherName();
                            parent.layer.close(index);
                        }
                    },
                    error:function (error) {
                        icModale(0, "系统错误，新建章节失败");
                    }
                });
            },
            success:function (index,layero) {//窗口加载成功

            }
        });
    }

    /**显示权限结构*/
    function showTree() {
        $("#ztree").removeClass("hide");
        $("#ztree").next().addClass("hide");
    }
});

/**
 * 显示和隐藏数据
 * @param treeObj
 */
function showHide(treeObj) {
    if ((treeObj).getNodes().length != 0) {
        $('#'+treeObj.setting.treeId).removeClass("hide");
        $('#'+treeObj.setting.treeId).next('div.noDataTipsBox').addClass('hide');
        treeObj.expandAll(true);
    } else {
        $('#'+treeObj.setting.treeId).addClass("hide");
        $('#'+treeObj.setting.treeId).next('div.noDataTipsBox').removeClass('hide');
    }
}

/**
 * 选择模块回调
 * @param mould 模块数据
 */
function  selectMouldCallback(mould) {
    var mouldIds = '';
    $.each(mould,function (index,m) {
        if(index < mould.length -1){
            mouldIds+=m.id+',';
        }else{
            mouldIds+=m.id;
        }
    });

    var courseId = $("#courseId").val();
    $.ajax({
        url:baseloaction +'/admin/course/catalog/saveCourseMould',
        type:'post',
        data:{
            'mouldIds':mouldIds
            ,'courseId':courseId
        },
        beforeSend:function () {
            icModale(1, "模块数据正在导入目录中，请不要进重复操作，请稍等片刻...",0);
        },
        dataType:'json',
        success:function (result) {
            if(result.success==true){
                var list = result.entity;
                if(list!=null && list.length>0){
                    var treeObj = $.fn.zTree.getZTreeObj("ztree");
                    treeObj.addNodes(null,list);
                    $.each(list,function (index,em) {
                        var nodeList = treeObj.getNodesByParam("id",em.id,null);
                        if(nodeList!=null && nodeList.length>0){
                            treeObj.expandNode(nodeList[0],true);
                            showHide(treeObj);
                        }
                    });
                    parent.layer.closeAll();
                }
            }else{
                icModale(0, result.message);
            }
        },
        error:function (error) {
            icModale(0, "系统错误，导入模块目录失败");
        }
    });
}

/**
 * 修改排序
 * @param currentId 要操作的节点ID
 * @param currentSort 操作的节点的新排序
 * @param oldId 被替换节点的ID
 * @param oldSort 被替换节点的排序
 * @param type 类型，1向前，2向后
 */
function updateNodeSort(currentId,currentSort,oldId,oldSort,type) {
    $.ajax({
        url: baseloaction +'/admin/course/catalog/updateNodeSort',
        type:'post',
        dataType:'json',
        data:{
            'currentId':currentId,
            'currentSort':currentSort,
            'oldId':oldId,
            'oldSort':oldSort
        },
        success:function (result) {
            if(result.success==true){
                var zTree = $.fn.zTree.getZTreeObj('ztree');
                var currentNode = zTree.getNodeByParam('id', currentId, null);
                currentNode.sort = currentSort;
                var oldNode = zTree.getNodeByParam('id', oldId, null);
                oldNode.sort = oldSort;
                zTree.updateNode(currentNode);
                zTree.updateNode(oldNode);
                if(type==1){//1向前
                    zTree.moveNode(oldNode, currentNode, "prev");
                }
                if(type==2){//2向后
                    zTree.moveNode(oldNode, currentNode, "next");
                }
                zTree.cancelSelectedNode(currentNode);
            }else{
                icModale(0,result.message);
            }
        },
        error:function (error) {
            icModale(0,'系统错误，调整节点排序失败');
        }
    });
}

/**
 * 设置排序
 * @param params 参数对象
 * @param id
 * @param parentId
 */
function setSortNum(params,id,parentId) {
    if(id <= 0){//表示添加
        var treeObj = $.fn.zTree.getZTreeObj("ztree");
        var sort = 0;
        if(parentId <= 0){//添加父级目录
            var parentList = treeObj.getNodes();
            if(parentList !=null && parentList.length >0){
                sort = parentList[parentList.length-1].sort;
            }
        }else{//添加子级目录
            var parentNode = treeObj.getNodeByParam('id', parentId, null);
            var childList = parentNode.children;
            if(childList!=null && childList.length>0){
                sort = childList[childList.length-1].sort;
            }
        }
        sort = sort +1;
        params.sort = sort;
    }
}


function  lookPractice(courseId){
    getRedirectMenu(baseloaction+"/admin/course/cou/coursePracticeList?courseId="+courseId);
}


//获取讲师数据
function  getTeacherName(){

    $.ajax({
        url:baseloaction +'/admin/course/cou/getTeacherName',
        type:'post',
        dataType:'json',
        data:{'courseId':$("#courseId").val()},
        success:function (result) {

            if(result.entity!=null&&result.entity.length>0){
                var html =""
                $.each(result.entity,function (index,obj) {
                    html+=' <button type="button" class="btn btn-sm btn-outline btn-default">'+obj.teacherName+'</button>'
                });
                $("#teacherName").html(html);
                $("#teacherMag").addClass("hide");
            }else{
                $("#teacherMag").removeClass("hide");
                $("#teacherName").html("");
            }
        },
        error:function (error) {
            icModale(0, "系统错误，获取讲师失败");
        }
    });

}


//计算时长
function sumDuration() {
    $.ajax({
        url:baseloaction +'/admin/course/cou/durationSum',
        type:'post',
        dataType:'json',
        data:{'courseId':$("#courseId").val()},
        success:function (result) {
            if(result.entity!=null){
                var html = longTimeToStr(result.entity.totleTimes);
                $("#durationSum").html(html);
                $("#durationMag").addClass("hide");
            }else{
                $("#durationMag").removeClass("hide");
                $("#durationSum").html("");
            }
        },
        error:function (error) {
            icModale(0, "系统错误，获取讲师失败");
        }
    });
}